import React from 'react';
import classNames from 'classnames';
import { Link } from 'react-router';

import {
  Button
} from 'react-bootstrap';

import * as Util from '../common/Util';

class Ticket extends React.Component {

  constructor() {
    super();
    this.state = {
      ticket_text : "获取验证码",
      ticket_progress : false
    }
  }

  static propTypes = {
      phone: React.PropTypes.string.isRequired,
      action : React.PropTypes.object.isRequired
  }

  static defaultProps = {
      phone : "",
      action : null
  }

  ticketCountDown(){
    let countdown = 119;
    this.timer = setInterval(function(){
      if(countdown == 0){
          clearInterval(this.timer);
          this.setState({
            ticket_text : '获取验证码',
            ticket_progress : false
          });
      }else{
        this.setState({
          ticket_text : `${countdown} 秒过期`
        });
        countdown --;
      }
    }.bind(this), 1000);
  }

  handleTicketClick(){
    if(this.state.ticket_progress === true){
       return;
    }

    this.setState({
      ticket_progress : true
    });

    let {phone, action} = this.props;
    //验证码发送
    action.fetchTicket(phone);

    this.ticketCountDown();
  }

  componentDidMount(){
    let { progress = false} = this.props;
    if (progress === true) {
      this.setState({
        ticket_text : "120 秒过期",
        ticket_progress : true
      });
      this.ticketCountDown();
    }
  }

  componentWillUnmount(){
    clearInterval(this.timer);
  }

  render() {

    let { phone, ticket_disabled = true } = this.props;

    if(Util.phoneValidate(phone)){
      ticket_disabled = false;
    }

    return (
        <Button 
          bsStyle="primary" 
          disabled={ ticket_disabled } 
          bsSize="small" 
          onClick={ this.handleTicketClick.bind(this) }>
            { this.state.ticket_text }
        </Button>
    );
  }
}

export default Ticket;
